package com.shuqi.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.PayModel;
import com.shuqi.model.bean.PayItemInfo;
import com.shuqi.model.bean.PayTypeAllInfo;
import com.shuqi.model.bean.PayTypeInfo;
import com.shuqi.model.net.listener.HttpRequestErrListener;
import com.shuqi.swiftp.Globals;

/**
 * 其他充值
 * 
 * @author chenwei
 * 
 */
public class PayOtherActivity extends ActivityBase implements OnClickListener, IEventListener,
        OnGroupExpandListener, OnChildClickListener, HttpRequestErrListener {

    private final static String TAG = "PayOtherActivity";

    private LinearLayout mLlError;// 显示网络错误错误的布局
    private TextView mTextRetry;// 网络错误重试

    private List<PayTypeInfo> mPayTypeInfos = new ArrayList<PayTypeInfo>();// 服务器返回的数据，两个列表
    private PayTypeAllInfo mPayTypeAllInfo;

    public final static int PAY_OTHER_HOME = 0;
    public final static int PAY_OTHER_HOME_SUCCESS = 1;
    public final static int PAY_HOME_NO_NETWORK = 2;
    public final static int PAY_HOME_INIT = 3;

    private ExpandableAdapter mExpandableAdapter;
    private ExpandableListView mExpandableListView;

    private String mStrModeId;// 分辨支付方式的id
    /** 进度圈 */
    private LinearLayout mLayoutLoading;
    private ActivityManager mActivityManager;
    private PayModel mPayModel;
    private ToastDialog mLoadingDialog;
    private CommonTitle mTitle;
    private ControlHandler handler = new ControlHandler(this) {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PAY_HOME_INIT:
                    activityLogicForward();
                    break;
                case PAY_HOME_NO_NETWORK:
                    mLlError.setVisibility(View.VISIBLE);
                    mLayoutLoading.setVisibility(View.GONE);
                    break;
                case PAY_OTHER_HOME:
                    mPayModel.getPayDatasByModeId(mStrModeId);
                    break;
                case PAY_OTHER_HOME_SUCCESS:
                    mLayoutLoading.setVisibility(View.GONE);
                    activityInitData();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_pay_other);

        mActivityManager = ActivityManager.getInstance();

        mPayModel = new PayModel(this);
        mPayModel.addEventListener(this);

        handler.sendEmptyMessage(PAY_HOME_INIT);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onEvent(int event, Object data) {
        Log4an.d(TAG, "event:" + event + ",result:" + data);
        Log4an.e("liyizhe", "==event===" + event);
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                if (data != null) {
                    mPayTypeAllInfo = (PayTypeAllInfo) data;
                    if (mPayTypeAllInfo != null) {
                        mPayTypeInfos = mPayTypeAllInfo.getPayTypeInfos();
                    }
                    handler.sendEmptyMessage(PAY_OTHER_HOME_SUCCESS);
                }
                break;
            default:
                handler.sendEmptyMessage(PAY_HOME_NO_NETWORK);
                break;
        }
    }

    @Override
    public void activityLogicForward() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        this.mLayoutLoading = (LinearLayout) findViewById(R.id.include_loading);
        mLoadingDialog = new ToastDialog(this);

        mLlError = (LinearLayout) findViewById(R.id.include_error);
        mTextRetry = (TextView) findViewById(R.id.retry);
        mTextRetry.setOnClickListener(this);

        mStrModeId = getIntent().getStringExtra("modeId");
        if ("2".equals(mStrModeId)) {
            mTitle.setTitle(getResources().getString(R.string.payother_phone_title));
        } else if ("3".equals(mStrModeId)) {
            mTitle.setTitle(getResources().getString(R.string.payother_game_title));
        }

        mExpandableListView = (ExpandableListView) findViewById(R.id.expandable_list_view);
        mExpandableListView.setOnChildClickListener(this);
        mExpandableListView.setOnGroupExpandListener(this);

        handler.sendEmptyMessage(PAY_OTHER_HOME);
        this.mLayoutLoading.setVisibility(View.VISIBLE);
    }

    @Override
    public void activityInitData() {
        if (mPayTypeAllInfo == null) {
            return;
        }
        if (PayModel.NET_NEEDLOGIN.equals(mPayTypeAllInfo.getCode())) {
            LoginActivity.openVerifyForResult(this, LoginActivity.LOGINTYPE_VERIFY);
            finish();
        } else if (mPayTypeInfos != null && PayModel.NET_SUCCESS.equals(mPayTypeAllInfo.getCode())) {
            mLlError.setVisibility(View.GONE);
            mExpandableAdapter = new ExpandableAdapter(PayOtherActivity.this, mPayTypeInfos);
            mExpandableListView.setAdapter(mExpandableAdapter);
            if (mPayTypeInfos != null && mPayTypeInfos.size() > 0) {
                mExpandableListView.expandGroup(0);
            }
        } else {
            mLoadingDialog.show(false, mPayTypeAllInfo.getMsg());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.retry:
//                if (!Util.isNetworkConnected(this)) {
//                    return;
//                }
//                this.mLayoutLoading.setVisibility(View.VISIBLE);
//                mLlError.setVisibility(View.GONE);
//                handler.sendEmptyMessage(PAY_OTHER_HOME);
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        mLayoutLoading.setVisibility(View.VISIBLE);
                        mLlError.setVisibility(View.GONE);
                        handler.sendEmptyMessage(PAY_OTHER_HOME);

                    }
                });
                break;
            case R.id.title_left:
                mActivityManager.finishActivity(this);
                break;
        }
    }

    @Override
    public void onGroupExpand(int groupPosition) {
        for (int i = 0; i < mExpandableAdapter.getGroupCount(); i++) {
            if (groupPosition != i) {
                mExpandableListView.collapseGroup(i);
            }
        }
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
            int childPosition, long id) {
        final PayTypeInfo payTypeInfo = mPayTypeInfos.get(groupPosition);
        final PayItemInfo payItemInfo = payTypeInfo.getPayItemInfos().get(childPosition);

        Intent intent = new Intent(PayOtherActivity.this, PayFormActivity.class);
        intent.putExtra("payTypeInfo", payTypeInfo);
        intent.putExtra("payItemInfo", payItemInfo);
        intent.putExtra("modeId", mStrModeId);
        ActivityManager.getInstance().startNextActivity(intent, PayOtherActivity.this);
        return false;
    }

    class ExpandableAdapter extends BaseExpandableListAdapter {

        Context context;
        private List<PayTypeInfo> groupArray;
        private LayoutInflater mInflater;

        public ExpandableAdapter(Context a, List<PayTypeInfo> groupArray) {
            context = a;
            this.mInflater = LayoutInflater.from(context);
            this.groupArray = groupArray;
        }

        public Object getChild(int groupPosition, int childPosition) {
            return groupArray.get(groupPosition).getPayItemInfos().get(childPosition);
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        public int getChildrenCount(int groupPosition) {
            return groupArray.get(groupPosition).getPayItemInfos().size();
        }

//        @SuppressLint("ResourceAsColor")
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                View convertView, ViewGroup parent) {
            final PayTypeInfo payTypeInfo = groupArray.get(groupPosition);
            final PayItemInfo payItemInfo = payTypeInfo.getPayItemInfos().get(childPosition);
            convertView = mInflater.inflate(R.layout.item_pay, null);

            TextView price = (TextView) convertView.findViewById(R.id.tv_price);
            TextView privilege = (TextView) convertView.findViewById(R.id.tv_privilege);
            TextView ppDou = (TextView) convertView.findViewById(R.id.tv_ppDou);
            TextView ppName = (TextView) convertView.findViewById(R.id.tv_ppName);

            price.setText(payItemInfo.getPrice());
            ppDou.setText(payItemInfo.getPpDou());
            ppName.setText(payItemInfo.getPpDouName());
            if (!"".equals(payItemInfo.getPrivilege())) {
                privilege.setText(payItemInfo.getPrivilege());
            } else {
                privilege.setVisibility(View.GONE);
            }

            return convertView;
        }

        public Object getGroup(int groupPosition) {
            return groupArray.get(groupPosition);
        }

        public int getGroupCount() {
            return groupArray.size();
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
                ViewGroup parent) {

            final PayTypeInfo bean = groupArray.get(groupPosition);
            convertView = mInflater.inflate(R.layout.item_pay_other, null);

            ImageView ivIconPay = (ImageView) convertView.findViewById(R.id.iv_icon_pay);
            String typeId = bean.getTypeId();
            int typeid = Integer.valueOf(typeId);
            int imageId = R.drawable.icon_p_alipay;
            switch (typeid) {
                case 1:
                    imageId = R.drawable.icon_p_yidong;
                    break;
                case 2:
                    imageId = R.drawable.icon_p_liantong;
                    break;
                case 3:
                    imageId = R.drawable.icon_p_dianxin;
                    break;
                case 4:
                    imageId = R.drawable.icon_p_junka;
                    break;
                case 5:
                    imageId = R.drawable.icon_p_shenda;
                    break;
                case 6:
                    imageId = R.drawable.icon_p_zhengtu;
                    break;
                case 7:
                    imageId = R.drawable.icon_p_wanmei;
                    break;
                default:
                    break;
            }
            ivIconPay.setImageDrawable(getResources().getDrawable(imageId));

            ImageView mgroupimage = (ImageView) convertView.findViewById(R.id.iv_ll);
            mgroupimage.setImageDrawable(getResources().getDrawable(R.drawable.expanded));
            if (!isExpanded) {
                mgroupimage.setImageDrawable(getResources().getDrawable(R.drawable.unexpanded));
            }

            TextView tvCardName = (TextView) convertView.findViewById(R.id.tv_card_name);
            tvCardName.setText(bean.getCardName());
            return convertView;
        }

        public boolean hasStableIds() {
            return false;
        }

        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        Globals.setContext(this);

    }

    @Override
    protected void onStop() {
        Globals.setContext(null);
        super.onStop();
    }

    @Override
    public void request_content_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_reponse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_format() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_net_error() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_timeout() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_url() {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            mActivityManager.finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        mPayTypeInfos = null;
        super.onDestroy();
    }

}
